package com.schoolhelper.comment.controller;

import com.schoolhelper.comment.domain.Comment;
import com.schoolhelper.comment.service.CommentService;
import com.schoolhelper.utils.Result;
import com.schoolhelper.utils.JwtUtils;
import com.schoolhelper.config.FileUploadConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/comments")
@CrossOrigin(origins = "http://localhost:8080")
public class CommentController {
    
    private static final Logger logger = LoggerFactory.getLogger(CommentController.class);
    
    @Autowired
    private CommentService commentService;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    @Autowired
    private FileUploadConfig fileUploadConfig;
    
    /**
     * 根据帖子ID获取评论列表（支持分页）
     */
    @GetMapping("/post/{postId}")
    public Result<List<Comment>> getCommentsByPostId(
            @PathVariable Long postId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "5") int size) {
        try {
            logger.info("获取帖子{}的评论列表，页码：{}，每页数量：{}", postId, page, size);
            List<Comment> comments = commentService.getCommentsByPostId(postId, page, size);
            
            // 处理评论中的头像URL
            for (Comment comment : comments) {
                if (comment.getAvatar() != null && !comment.getAvatar().isEmpty()) {
                    // 如果头像不是完整URL，则拼接完整URL
                    if (!comment.getAvatar().startsWith("http")) {
                        comment.setAvatar(fileUploadConfig.getFileUrl(comment.getAvatar()));
                    }
                }
            }
            
            return Result.success(comments);
        } catch (Exception e) {
            logger.error("获取评论列表失败", e);
            return Result.error("获取评论列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加评论
     */
    @PostMapping
    public Result<Comment> addComment(@RequestBody Comment comment, HttpServletRequest request) {
        try {
            // 从请求头获取JWT token并解析用户ID
            String authHeader = request.getHeader("Authorization");
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return Result.error("用户未认证");
            }
            
            String token = authHeader.substring(7);
            Long userId = jwtUtils.getUserIdFromToken(token);
            if (userId == null) {
                return Result.error("无效的认证信息");
            }
            
            comment.setUserId(userId);
            
            logger.info("用户{}添加评论到帖子{}", userId, comment.getPostId());
            
            // 验证评论内容
            if (comment.getContent() == null || comment.getContent().trim().isEmpty()) {
                return Result.error("评论内容不能为空");
            }
            
            if (comment.getContent().length() > 500) {
                return Result.error("评论内容不能超过500字符");
            }
            
            Comment createdComment = commentService.addComment(comment);
            return Result.success(createdComment);
            
        } catch (Exception e) {
            logger.error("添加评论失败", e);
            return Result.error("添加评论失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除评论（软删除）
     */
    @DeleteMapping("/{commentId}")
    public Result<String> deleteComment(@PathVariable Long commentId, HttpServletRequest request) {
        try {
            // 从请求头获取JWT token并解析用户ID
            String authHeader = request.getHeader("Authorization");
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return Result.error("用户未认证");
            }
            
            String token = authHeader.substring(7);
            Long userId = jwtUtils.getUserIdFromToken(token);
            if (userId == null) {
                return Result.error("无效的认证信息");
            }
            
            logger.info("用户{}删除评论{}", userId, commentId);
            
            boolean success = commentService.deleteComment(commentId, userId);
            if (success) {
                return Result.success("评论删除成功");
            } else {
                return Result.error("删除失败，评论不存在或无权限删除");
            }
            
        } catch (Exception e) {
            logger.error("删除评论失败", e);
            return Result.error("删除评论失败: " + e.getMessage());
        }
    }
}